const { exec } = require('child_process');

module.exports = {
  copy: (text) => {
    return new Promise((resolve, reject) => {
      const platform = process.platform;
      let command;
      
      try {
        // 安全处理特殊字符
        const safeText = text.replace(/"/g, '\\"').replace(/\$/g, '\\$').replace(/`/g, '\\`');
        
        if (platform === 'win32') {
          // Windows 命令
          command = `chcp 65001 > nul && echo ${safeText} | clip`;
        } else if (platform === 'darwin') {
          // macOS 命令
          command = `echo "${safeText}" | pbcopy`;
        } else {
          // Linux 命令
          command = `echo "${safeText}" | xclip -selection clipboard -i`;
        }
        
        exec(command, (error, stdout, stderr) => {
          if (error || stderr) {
            reject(new Error(`剪贴板操作失败: ${error?.message || stderr}`));
          } else {
            resolve(true);
          }
        });
      } catch (err) {
        reject(new Error(`剪贴板初始化错误: ${err.message}`));
      }
    });
  }
};